<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Product extends CI_Controller {

	public function index() {
		$this -> pages();
	}

	public function pages() {
		
		//clear session of search data function
		if ($this -> input -> get('search')) {
			$this -> session -> unset_userdata('search');
		}

		$data['title'] = "List feature products";

		$data['categories'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "categories");
		$data['brands'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "brands");
		// select slide promotion to display on home page website
		$data['slides']=$this->mod_globals->select_all(PREFIX_TABLE."slide_promotions");

		//Config pagination with feature product
		$this -> load -> library('pagination');
		$config = array();
		$config["base_url"] = base_url() . "product/pages";
		
		//select count total row of product post
		$config["total_rows"] = $this -> mod_globals -> select_join_count(PREFIX_TABLE . "products", $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", NULL);
		$config["per_page"] = 9;
		$config["uri_segment"] = 3;
		$config["num_links"] = round($config["total_rows"] / $config["per_page"]);

		$this -> pagination -> initialize($config);

		$page = ($this -> uri -> segment(3)) ? $this -> uri -> segment(3) : 0;
		//Select product page display depend on your pagination config in each page
		$data['products'] = $this -> mod_globals -> select_join_get_only_fields(PREFIX_TABLE . "products", $arr_field = array(PREFIX_TABLE . 'products.name AS pro_name', 'key_code', 'price', 'description','view', PREFIX_TABLE . "product_images.name AS img_name"), $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", NULL, $config["per_page"] . "," . $page, "product_id desc");
		$data["pagination"] = $this -> pagination -> create_links();
		$this -> load -> view(F_MASTER . 'index', $data);
	}

	//Function for browsing product display by product category
	public function category() {
		$data['title'] = "List products by category";
		$category_name = (!$this -> uri -> segment(3) ? "" : $this -> uri -> segment(3));

		$category_id = $this -> mod_globals -> select_string(PREFIX_TABLE . "categories", "category_id", array("name" => $category_name));

		$data['categories'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "categories");
		$data['brands'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "brands");
		
		//Option to filter product by category with limit data display
		if ($this -> input -> get('limit')) {
			$limit = $this -> input -> get('limit');
		} else {
			$limit = NULL;
		}
		//Option to filter product sort with name,price and rating, including prevent spam access url
		if ($this -> input -> get('sort') && $this -> input -> get('order') ) {
			
			if($this -> input -> get('sort')!="name" && $this -> input -> get('sort')!="price" && $this -> input -> get('sort')!="rating"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2)."/".$this->uri->segment(3));
			}else if($this -> input -> get('order') !="ASC" && $this -> input -> get('order') !="DESC"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2)."/".$this->uri->segment(3));
			}
			
			$sort = PREFIX_TABLE . "products." . $this -> input -> get('sort') . " " . $this -> input -> get('order');
		} else {
			$sort = "product_id desc";
		}

		//config pagination with dynamic url display product by page and filter,limit,sort,and order
		$this -> load -> library('pagination');
		$config['base_url'] = base_url() . "product/category/$category_name/?filter=true";
		foreach ($_GET as $key => $value) {
			if ($key != 'filter' && $key != 'offset') {
				$config['base_url'] .= '&' . $key . '=' . $value;
			}
		}

		//allow offset url get to display product page
		$config['query_string_segment'] = 'offset';
		$config['page_query_string'] = true;

		$config['total_rows'] = $this -> mod_globals -> select_join_count(PREFIX_TABLE . "products", $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.use_category_id" => $category_id, PREFIX_TABLE . "product_images.priority" => 1), $limit);
		$config['per_page'] = $number_per_page = 15;

		//Checking if empty offset and set default offset value
		if (!empty($_GET['offset'])) {
			$offset = $_GET['offset'];
		} else {
			$offset = 0;
		}

		$this -> pagination -> initialize($config);
		//Select product display with config pagination including filter,limit,sort and order
		$data['products'] = $this -> mod_globals -> select_join_get_only_fields(PREFIX_TABLE . "products", $arr_field = array(PREFIX_TABLE . 'products.name AS pro_name', 'key_code', 'price', 'description','view',PREFIX_TABLE . "product_images.name AS img_name"), $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.use_category_id" => $category_id, PREFIX_TABLE . "product_images.priority" => 1), $config["per_page"] . "," . $offset, $sort);
		$data["pagination"] = $this -> pagination -> create_links();

		$this -> load -> view(F_MASTER . 'index', $data);
	}

	//This function use to display product by brand but this function we skip, u can custom it more by yourself
	public function brand() {
		$data['title'] = "List products by brand ";
		$data['categories'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "categories");
		$data['brands'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "brands");

		$brand_id = $this -> uri -> segment(3);
		$category_id = $this -> mod_globals -> select_string(PREFIX_TABLE . "categories", "category_id", array("use_brand_id" => $brand_id));

		echo $category_id;
		exit ;

		$this -> load -> library('pagination');
		$config = array();
		$config["base_url"] = base_url() . "product/brand";
		$config["total_rows"] = $this -> mod_globals -> select_join_count(PREFIX_TABLE . "products", $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.use_category_id" => $category_id, PREFIX_TABLE . "product_images.priority" => 1));
		$config["per_page"] = 15;
		$config["uri_segment"] = 3;
		$config["num_links"] = round($config["total_rows"] / $config["per_page"]);

		$this -> pagination -> initialize($config);

		$page = ($this -> uri -> segment(3)) ? $this -> uri -> segment(3) : 0;
		$data['products'] = $this -> mod_globals -> select_join_get_only_fields(PREFIX_TABLE . "products", $arr_field = array(PREFIX_TABLE . 'products.name AS pro_name', 'key_code', 'price', 'description', 'view',PREFIX_TABLE . "product_images.name AS img_name"), $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.use_category_id" => $category_id, PREFIX_TABLE . "product_images.priority" => 1), $config["per_page"] . "," . $page, "product_id desc");
		$data["pagination"] = $this -> pagination -> create_links();
		$this -> load -> view(F_MASTER . 'index', $data);
	}

	//Function to list product for sale that user have posted in our website
	public function product_for_sale() {
		$data['title'] = "List product for sale";
		$data['categories'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "categories");
		$data['brands'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "brands");

		//Option to filter product sale with limit data display
		if ($this -> input -> get('limit')) {
			$limit = $this -> input -> get('limit');
		} else {
			$limit = NULL;
		}
		
		//Option to filter product sort with name,price and rating, including prevent spam access url
		if ($this -> input -> get('sort') && $this -> input -> get('order')) {
			
			if($this -> input -> get('sort')!="name" && $this -> input -> get('sort')!="price" && $this -> input -> get('sort')!="rating"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2));
			}else if($this -> input -> get('order') !="ASC" && $this -> input -> get('order') !="DESC"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2));
			}
			
			$sort = PREFIX_TABLE . "products." . $this -> input -> get('sort') . " " . $this -> input -> get('order');
		} else {
			$sort = "product_id desc";
		}

		//config pagination with dynamic url display product by page and filter,limit,sort,and order
		$this -> load -> library('pagination');
		$config['base_url'] = base_url() . "product/product-for-sale/?filter=true";
		foreach ($_GET as $key => $value) {
			if ($key != 'filter' && $key != 'offset') {
				$config['base_url'] .= '&' . $key . '=' . $value;
			}
		}
		//allow offset url get to display product page
		$config['query_string_segment'] = 'offset';
		$config['page_query_string'] = true;

		$config['total_rows'] = $this -> mod_globals -> select_join_count(PREFIX_TABLE . "products", $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.use_product_function_id" => 4, PREFIX_TABLE . "product_images.priority" => 1), $limit);
		$config['per_page'] = $number_per_page = 15;
		
		//Checking if empty offset and set default offset value
		if (!empty($_GET['offset'])) {
			$offset = $_GET['offset'];
		} else {
			$offset = 0;
		}

		$this -> pagination -> initialize($config);
		//Select product display with config pagination including filter,limit,sort and order
		$data['products'] = $this -> mod_globals -> select_join_get_only_fields(PREFIX_TABLE . "products", $arr_field = array(PREFIX_TABLE . 'products.name AS pro_name', 'key_code', 'price', 'description','view', PREFIX_TABLE . "product_images.name AS img_name"), $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.use_product_function_id" => 4, PREFIX_TABLE . "product_images.priority" => 1), $config["per_page"] . "," . $offset, $sort);
		$data["pagination"] = $this -> pagination -> create_links();

		$this -> load -> view(F_MASTER . 'index', $data);
	}
	
	//Function to list product for buy that user have posted in our website
	public function product_for_buy() {
		$data['title'] = "List products for buy";
		$data['categories'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "categories");
		$data['brands'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "brands");

		//Option to filter product for buy with limit data display
		if ($this -> input -> get('limit')) {
			$limit = $this -> input -> get('limit');
		} else {
			$limit = NULL;
		}

		//Option to filter product sort with name,price and rating, including prevent spam access url
		if ($this -> input -> get('sort') && $this -> input -> get('order')) {
			if($this -> input -> get('sort')!="name" && $this -> input -> get('sort')!="price" && $this -> input -> get('sort')!="rating"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2));
			}else if($this -> input -> get('order') !="ASC" && $this -> input -> get('order') !="DESC"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2));
			}
			
			$sort = PREFIX_TABLE . "products." . $this -> input -> get('sort') . " " . $this -> input -> get('order');
		} else {
			$sort = "product_id desc";
		}
		
		//config pagination with dynamic url display product by page and filter,limit,sort,and order
		$this -> load -> library('pagination');
		$config['base_url'] = base_url() . "product/product-for-buy/?filter=true";
		foreach ($_GET as $key => $value) {
			if ($key != 'filter' && $key != 'offset') {
				$config['base_url'] .= '&' . $key . '=' . $value;
			}
		}

		//allow offset url get to display product page
		$config['query_string_segment'] = 'offset';
		$config['page_query_string'] = true;

		$config['total_rows'] = $this -> mod_globals -> select_join_count(PREFIX_TABLE . "products", $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.use_product_function_id" => 5, PREFIX_TABLE . "product_images.priority" => 1), $limit);
		$config['per_page'] = $number_per_page = 15;
		
		//Checking if empty offset and set default offset value
		if (!empty($_GET['offset'])) {
			$offset = $_GET['offset'];
		} else {
			$offset = 0;
		}

		$this -> pagination -> initialize($config);
		//Select product display with config pagination including filter,limit,sort and order
		$data['products'] = $this -> mod_globals -> select_join_get_only_fields(PREFIX_TABLE . "products", $arr_field = array(PREFIX_TABLE . 'products.name AS pro_name', 'key_code', 'price', 'description','view', PREFIX_TABLE . "product_images.name AS img_name"), $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.use_product_function_id" => 5, PREFIX_TABLE . "product_images.priority" => 1), $config["per_page"] . "," . $offset, $sort);
		$data["pagination"] = $this -> pagination -> create_links();

		$this -> load -> view(F_MASTER . 'index', $data);
	}

	// This function use to display that user post with other options that we provide to user to select for product function that they want to used(for sale,for buy and other). But we don't implement it yet, You can custom it if you required this option
	public function product_for_other() {
		$data['title'] = "List product for others";
		$data['categories'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "categories");
		$data['brands'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "brands");
		$this -> load -> view(F_MASTER . 'index', $data);
	}

	//Function use to display product detail information of product post.
	public function detail($key_id) {
		$data['title'] = "Preview product detail";
		
		
		$data['categories'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "categories");
		$data['brands'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "brands");
		
		//Select product information of this product id
		$data['product_info'] = $this -> mod_globals -> select_where(PREFIX_TABLE . "products", array(PREFIX_TABLE . "products.key_code" => $key_id));
		//Select the number of current view
		$cur_view_number=$this->mod_globals->select_string(PREFIX_TABLE."products","view",array("key_code"=>$key_id));
		//Update to increase number of view
		$this->mod_globals->update(PREFIX_TABLE."products",array("view"=>$cur_view_number+1),array("key_code"=>$key_id));
		
		
		if($data['product_info']->num_rows()==1){
			$product_id=$data['product_info'] -> row() -> product_id;
			$use_category_id=$data['product_info'] -> row() -> use_category_id;
			$product_name=$data['product_info'] -> row() -> name;
		}else{
			$use_category_id=0;
			$product_id=0;
			$product_name="";
		}
		
		// Splite product name to find related product that have the same name like this
		$search_related=array();    
		 $terms=explode(" ",$product_name);
		 $i=1;
		 foreach($terms as $v){
		 	$search_related[]=$v;
			 $i++;
		 }
		
		$related_array_like=array(PREFIX_TABLE . "products.name" => $search_related);
		
		$ip = $_SERVER["REMOTE_ADDR"];
		$data['ratings']=$this->mod_globals->select_where(PREFIX_TABLE."ratings",array("use_product_id"=>$product_id));
		//SHOWS THE USER'S RATING, IF RATING HAS BEEN SUBMITTED BEFORE
		$data['rating_submit']=$this->mod_globals->select_where(PREFIX_TABLE."ratings",array("use_product_id"=>$product_id,"ip"=>$ip));
		
		// Select all product image of this product item
		$data['product_images'] = $this -> mod_globals -> select_where(PREFIX_TABLE . "product_images", array(PREFIX_TABLE . "product_images.use_product_id" => $product_id));
		//$data['product_related'] = $this -> mod_globals -> select_join_like_get_only_fields(PREFIX_TABLE . "products", $arr_field = array(PREFIX_TABLE . 'products.name AS pro_name', 'key_code', 'price', 'description', PREFIX_TABLE . "product_images.name AS img_name"), $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", $related_array_likearray(PREFIX_TABLE . "products.use_category_id" => $use_category_id,PREFIX_TABLE."products.name"=>$product_name, PREFIX_TABLE . "product_images.priority" => 1), 5, "view desc");
		//Query to select product related with the name of product
		$data['product_related'] = $this -> mod_globals -> select_join_like_or_get_only_fields(PREFIX_TABLE . "products", $arr_field = array(PREFIX_TABLE . 'products.name AS pro_name', 'key_code', 'price', 'description', PREFIX_TABLE . "product_images.name AS img_name"), $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", $related_array_like,array(PREFIX_TABLE . "product_images.priority" => 1), 5, "view desc");
		$this -> load -> view(F_MASTER . 'index', $data);
	}

	//Function search product with pagination,filter option and friendly url
	public function search_query() {

		$data['title'] = "Result for search products";
		$data['categories'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "categories");
		$data['brands'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "brands");
		
		//Option to filter product for buy with limit data display
		if ($this -> input -> get('limit')) {
			$limit = $this -> input -> get('limit');
		} else {
			$limit = NULL;
		}
		
		//Option to filter product sort with name,price and rating, including prevent spam access url
		if ($this -> input -> get('sort') && $this -> input -> get('order')) {
			if($this -> input -> get('sort')!="name" && $this -> input -> get('sort')!="price" && $this -> input -> get('sort')!="rating"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2));
			}else if($this -> input -> get('order') !="ASC" && $this -> input -> get('order') !="DESC"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2));
			}
			
			$sort = PREFIX_TABLE . "products." . $this -> input -> get('sort') . " " . $this -> input -> get('order');
		} else {
			$sort = "product_id desc";
		}

		$search = $this -> input -> get('search-data');
		/*$search_like=array();    
		 $terms=explode(" ",$search);
		 $i=1;
		 foreach($terms as $v){
		 	$search_like[]=$v;
			 $i++;
		 }*/
		
		/*$test=array(PREFIX_TABLE . "products.name" => $search_like);
		$i=0;
		foreach ($test as $field => $value) {
			foreach($value as $v){
				echo $field."===$i===".$v."<br />";	
				$i++;
			}
		}
		*/
		/* search engine optimize 
		 * 
		 * $terms=explode(" ",$search);
		 * $query="SELECT * FROM search WHERE ";
		 * $i=0;
		 * foreach($terms as $each){
		 * 		$i++;
		 * 		if($i==1){
		 * 			$query.="keywords LIKE '%$each%' ";
		 * 		}else{
		 * 			$query.="OR keywords LIKE '%$each%' ";
		 * 		}
		 * }
		 * $query=mysql_query($query);
		 * 
		 * 
		 * 
		 * 
		 * */

		//config pagination with dynamic url display product by page and filter,limit,sort,and order
		$this -> load -> library('pagination');
		$config['base_url'] = base_url() . "product/search-query/?search=true";

		// as we are unsure as to what values are going to passed to your pagination page
		// we need to build the base url on the fly
		foreach ($_GET as $key => $value) {
			if ($key != 'search' && $key != 'offset') {
				$config['base_url'] .= '&' . $key . '=' . $value;
			}
		}

		//this will need to go to a model method which determines the total number of results
		//based on your form/search parameters. In my case the model method takes an array which in this case
		//is based on key/value pairs that are same mapped the same as the form inputs
		//$results_info = $this->m_db_results->search($_GET);

		//the key to using this is that it will append your uri with the query string segment parameter
		//using this allows in conjunction with the $config['page_query_string'] being set to true
		//as it adds the offset to the URI as &offset=x
		$config['query_string_segment'] = 'offset';
		$config['page_query_string'] = true;

		$config['total_rows'] = $this -> mod_globals -> select_join_like(PREFIX_TABLE . "products", $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.name" => $search), array(PREFIX_TABLE . "product_images.priority" => 1),$limit) -> num_rows();
		$config['per_page'] = $number_per_page = 15;

		//now instead of using the uri segment to determine the number of results we offset
		//from our results we use the parameter we specified above in the $config['query_string_segment']
		if (!empty($_GET['offset'])) {
			$offset = $_GET['offset'];
		} else {
			$offset = 0;
		}

		//now we run the same method as above but we supply an amount of results we want to be returned and the offset
		//as the second and third parameters
		//and pass off the data to our view
		$this -> pagination -> initialize($config);
		$data['products'] = $this -> mod_globals -> select_join_like_get_only_fields(PREFIX_TABLE . "products", $arr_field = array(PREFIX_TABLE . 'products.name AS pro_name', 'key_code', 'price', 'description','view', PREFIX_TABLE . "product_images.name AS img_name"), $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", array(PREFIX_TABLE . "products.name" => $search), array(PREFIX_TABLE . "product_images.priority" => 1), $config["per_page"] . "," . $offset, $sort);
		//$data['results'] = $this->m_db_results->search($_GET, $number_per_page, $offset);
		$data["pagination"] = $this -> pagination -> create_links();

		$this -> load -> view(F_MASTER . 'index', $data);
	}

	public function view_all_products() {
		$data['title'] = "List products";

		$data['categories'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "categories");
		$data['brands'] = $this -> mod_globals -> select_all(PREFIX_TABLE . "brands");

		//Option to filter product for buy with limit data display
		if ($this -> input -> get('limit')) {
			$limit = $this -> input -> get('limit');
		} else {
			$limit = NULL;
		}

		//Option to filter product sort with name,price and rating, including prevent spam access url
		if ($this -> input -> get('sort') && $this -> input -> get('order')) {
			
			if($this -> input -> get('sort')!="name" && $this -> input -> get('sort')!="price" && $this -> input -> get('sort')!="rating"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2));
			}else if($this -> input -> get('order') !="ASC" && $this -> input -> get('order') !="DESC"){
				redirect($this->uri->segment(1)."/".$this->uri->segment(2));
			}
			
			$sort = PREFIX_TABLE . "products." . $this -> input -> get('sort') . " " . $this -> input -> get('order');
		} else {
			$sort = "product_id desc";
		}
		
		//config pagination with dynamic url display product by page and filter,limit,sort,and order
		$this -> load -> library('pagination');
		$config['base_url'] = base_url() . "product/view-all-products/?filter=true";
		foreach ($_GET as $key => $value) {
			if ($key != 'filter' && $key != 'offset') {
				$config['base_url'] .= '&' . $key . '=' . $value;
			}
		}
		
		//the key to using this is that it will append your uri with the query string segment parameter
		//using this allows in conjunction with the $config['page_query_string'] being set to true
		//as it adds the offset to the URI as &offset=x
		$config['query_string_segment'] = 'offset';
		$config['page_query_string'] = true;

		$config['total_rows'] = $this -> mod_globals -> select_join_count(PREFIX_TABLE . "products", $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", NULL, $limit);
		$config['per_page'] = $number_per_page = 6;

		//now instead of using the uri segment to determine the number of results we offset
		//from our results we use the parameter we specified above in the $config['query_string_segment']
		if (!empty($_GET['offset'])) {
			$offset = $_GET['offset'];
		} else {
			$offset = 0;
		}

		$this -> pagination -> initialize($config);
		// Select product display depend on page depend on your pagination config
		$data['products'] = $this -> mod_globals -> select_join_get_only_fields(PREFIX_TABLE . "products", $arr_field = array(PREFIX_TABLE . 'products.name AS pro_name', 'key_code', 'price', 'description','view', PREFIX_TABLE . "product_images.name AS img_name"), $arr_join = array(PREFIX_TABLE . 'product_images' => array('product_id' => 'use_product_id')), $join_type = "INNER", NULL, $config["per_page"] . "," . $offset, $sort);
		$data["pagination"] = $this -> pagination -> create_links();

		$this -> load -> view(F_MASTER . 'index', $data);
	}

	//Search data handle to store with session for remember to diplay with pagination of your search
	public function search_product_handler($search) {
		if ($search) {
			$this -> session -> set_userdata('search', $search);
			return $search;
		} else if ($this -> session -> userdata('search')) {
			$search = $this -> session -> userdata('search');
			return $search;
		} else {
			$search = "";
			return $search;
		}
	}
	
	// Function using to rating product when click rating product on page detail
	public function rate(){
		
		$id = $_POST["id"]; //ID OF THE CONTENT
		$rating = $_POST["rating"]; //RATING THAT THE USER HAS SUBMITTED
		$ip = $_SERVER["REMOTE_ADDR"]; //IP ADDRESS OF THE USER
		$date = date("l, F j, Y"). " at " .date("h:i:s A"); //DATE & TIME
		$timestamp = time(); //TIMESTAMP
		
		//CHECKS TO SEE IF USER HAS ALREADY RATED THE CONTENT
		$q=$this->mod_globals->select_where(PREFIX_TABLE."ratings",array("use_product_id"=>$id,"ip"=>$ip));
		$n = $q->num_rows();
		
		
		//IF USER HAS ALREADY RATED CONTENT...
		if($n){
		    //CHECKS TO SEE IF THE RATING IS THE SAME AS BEFORE
		    if($rating!=$q->row()->rating){
		        //IF SO, THE RATING WILL BE UPDATED
		        $this->mod_globals->update(PREFIX_TABLE."ratings",array("rating"=>$rating,"dateposted"=>$date,"timestamp"=>$timestamp),array("use_product_id"=>$id,"ip"=>$ip));
		        //mysql_query("UPDATE $ratings SET rating='$rating', dateposted='$date', timestamp='$timestamp' WHERE id='$id' AND ip='$ip'");
		        
		        $ratings=$this->mod_globals->select_where(PREFIX_TABLE."ratings",array("use_product_id"=>$id));
				
				$n=$ratings->num_rows();
				$x=0;
		        foreach($ratings->result() as $r){
					$rr = $r->rating; //EACH RATING FOR THE CONTENT
					$x += $rr; //ADDS THEM ALL UP
				}
				//IF THERE ARE RATINGS...
				if($n){
					$rating = $x/$n; //THE AVERAGE RATING (UNROUNDED)
				} else {
					$rating = 0; //SET TO PREVENT THE ERROR OF DIVISION BY 0, WHICH WOULD BE THE NUMBER OF RATINGS HERE
				}
				$dec_rating = round($rating, 1); //ROUNDED RATING TO THE NEAREST TENTH			
				$this->mod_globals->update(PREFIX_TABLE."products",array("rating"=>$dec_rating),array("product_id"=>$id));	
		    }
		} else {
		    //ADDS THE NEW RATING IF USER HAS NOT ALREADY RATED
		    	$this->mod_globals->insert(PREFIX_TABLE."ratings",array("use_product_id"=>$id,"rating"=>$rating,"ip"=>$ip,"dateposted"=>$date,"timestamp"=>$timestamp,"created_date"=>null));
		    	//mysql_query("INSERT INTO $ratings VALUES('', '$id', '$rating', '$ip', '$date', '$timestamp')");
		    	
		    	$ratings=$this->mod_globals->select_where(PREFIX_TABLE."ratings",array("use_product_id"=>$id));
				
				$n=$ratings->num_rows();
				$x=0;
		        foreach($ratings->result() as $r){
					$rr = $r->rating; //EACH RATING FOR THE CONTENT
					$x += $rr; //ADDS THEM ALL UP
				}
				//IF THERE ARE RATINGS...
				if($n){
					$rating = $x/$n; //THE AVERAGE RATING (UNROUNDED)
				} else {
					$rating = 0; //SET TO PREVENT THE ERROR OF DIVISION BY 0, WHICH WOULD BE THE NUMBER OF RATINGS HERE
				}
				$dec_rating = round($rating, 1); //ROUNDED RATING TO THE NEAREST TENTH			
				$this->mod_globals->update(PREFIX_TABLE."products",array("rating"=>$dec_rating),array("product_id"=>$id));
		}
		
		$ratings=$this->mod_globals->select_where(PREFIX_TABLE."ratings",array("use_product_id"=>$id));
		//SHOWS THE USER'S RATING, IF RATING HAS BEEN SUBMITTED BEFORE
		$rating_submit=$this->mod_globals->select_where(PREFIX_TABLE."ratings",array("use_product_id"=>$id,"ip"=>$ip));
		
		
								$n=$ratings->num_rows();//NUMBER OF VOTES
								if($n==1){
								    $v = 'vote';
								} else {
								    $v = 'votes';
								}
								$x=0;
								foreach($ratings->result() as $r){
								    $rr = $r->rating; //EACH RATING FOR THE CONTENT
								    $x += $rr; //ADDS THEM ALL UP
								}
								//IF THERE ARE RATINGS...
								if($n){
								    $rating = $x/$n; //THE AVERAGE RATING (UNROUNDED)
								} else {
								    $rating = 0; //SET TO PREVENT THE ERROR OF DIVISION BY 0, WHICH WOULD BE THE NUMBER OF RATINGS HERE
								}
								$dec_rating = round($rating, 1); //ROUNDED RATING TO THE NEAREST TENTH
								//SHOWS THE FULL NUMBER OF STARS (Ex: 3.5 stars = 3 full stars)
								$stars="";
								for($i=1; $i<=floor($rating); $i++){
								    $stars .= '<div class="star" id="'.$i.'"></div>';
								}
								
								//SHOWS THE USER'S RATING, IF RATING HAS BEEN SUBMITTED BEFORE
								if($rating_submit->num_rows>0){
									$y = 'You rated this <b>'.$rating_submit->row()->rating.'</b>';
								}else{
									$y="";
								}
								//THE OVERALL RATING (THE OPAQUE STARS)
								echo '<div class="r">
								<div class="rating">'.$stars.'</div>';
								
								//THE TRANSPARENT STARS (OPAQUE STARS WILL COVER AS MANY STARS AS THE RATING REPRESENTS)
								echo '<div class="transparent">
								<div class="star" id="1"></div>
								<div class="star" id="2"></div>
								<div class="star" id="3"></div>
								<div class="star" id="4"></div>
								<div class="star" id="5"></div>
								<div class="votes">('.$dec_rating.'/5, '.$n.' '.$v.') '.$y.'</div>
								</div>
								
								</div>';						
		
	}
}
